package cn.stylefeng.guns.modular.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

public class JstSignUtil {

    private static Logger logger = LoggerFactory.getLogger(JstSignUtil.class);

    private JstSignUtil() {}

    public static String getSign(String app_secret, Map<String, String> params) {
        try {
            String sortedStr = getSortedParamStr(params);
            String paraStr = app_secret + sortedStr;

            return createSign(paraStr);
        } catch (UnsupportedEncodingException e) {
            logger.error("getSign UnsupportedEncodingException ", e);
        }

        return StringUtils.EMPTY;
    }

    /**
     * 构造自然排序请求参数
     *
     * @param params 请求
     * @return 字符串
     */
    private static String getSortedParamStr(Map<String, String> params) throws UnsupportedEncodingException {
        Set<String> sortedParams = new TreeSet<>(params.keySet());

        StringBuilder strB = new StringBuilder();
        // 排除sign和空值参数
        for (String key : sortedParams) {
            if ("sign".equalsIgnoreCase(key)) {
                continue;
            }

            String value = params.get(key);

            if (StringUtils.isNotEmpty(value)) {
                strB.append(key).append(value);
            }
        }
        return strB.toString();
    }

    /**
     * 生成新sign
     *
     * @param str 字符串
     * @return String
     */
    private static String createSign(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(str.getBytes("UTF-8"));

            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            int i = 0;
            while (i < j) {
                byte byte0 = md[i];
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
                i++;
            }
            return new String(buf);
        } catch (Exception e) {
            logger.error("create sign was failed", e);
            return null;
        }
    }
}

/**
 // 实例化client
 ApiClient client = new DefaultApiClient();
 // 设置超时时间
 //        ((DefaultApiClient)client).setReadTimeout(3000);
 //        ((DefaultApiClient)client).setConnectTimeout(2000);

 // 替换为POP分配给应用的app_key,app_secret,accessToken等
 String url = "https://dev-api.jushuitan.com/open/shops/query";// 示例为测试地址，生产上请替换为正式地址
 String appKey = "b0b7d1db226d4216a3d58df9ffa2dde5";
 String appSecret = "99c4cef262f34ca882975a7064de0b87";
 String accessToken = "b70b7d7fef5341a6bc06e25e2aae1e85";
 String biz = "{\"shop_id\":10187992,\"sku_ids\":\"lyyi001,lyyi002\",\"page_index\":1,\"page_size\":30}";
 // 构建请求对象
 ApiRequest request = new ApiRequest.Builder(url, appKey, appSecret)
 .biz(biz).build();

 // 执行接口调用
 try {
 ApiResponse response = client.execute(request, accessToken);
 System.out.println("is success: " + response.isSuccess());
 System.out.println("body: " + response.getBody());
 } catch (ApiException e) {
 switch (e.getCodeEnum()) {
 case SYS_ERROR:
 // TODO retry
 break;
 case PARAM_ERROR:
 // TODO check param
 break;
 case SIGN_ERROR:
 // TODO @see com.jushuitan.api.util.ApiUtil
 break;
 case CONNECT_ERROR:
 // TODO check network
 break;
 case TIME_OUT_ERROR:
 // TODO check logic or reset readTimeout
 break;
 case EXECUTE_ERROR:
 // TODO @see com.jushuitan.api.DefaultApiClient#executeRemote
 break;
 default:
 // log
 break;
 }
 } catch (Exception e) {
 // exception handle
 }
 **/